import React, { useMemo, useEffect, useState } from 'react';
import s from './style.module.css';
import { withRouter } from 'react-router';
import PropTypes from 'prop-types';
import Table from '@knownsec/react-component/dist/Table';
import Tooltip from '@knownsec/react-component/dist/Tooltip';
import EmptyData from '../../../../../../components/empty/EmptyData';
import Pagination from '@knownsec/react-component/dist/Pagination';
import {
	getParams,
	turnToUrlparam,
} from '../../../../../../helpers/getUrlParams';
import cn from 'classnames';
import { Link } from 'react-router-dom';
import Button from '@knownsec/react-component/dist/Button';
import Input from '@kuiper-components/input';
import Icon from '@knownsec/react-component/dist/Icon';
import fetchFer from 'API/fetch';
import CopyBoard from '../../../../../../components/CopyBoard';
import Select, { Option } from '@kuiper-components/select';
import { Search24 as SearchIcon } from '@carbon/icons-react';
import { cloneDeep } from 'lodash';
import moment from 'moment';
import IgnoreRiskConfirm from '../../../../../../components/IgnoreRiskDialog';

const optionData = [
	{ label: '高危', value: '4' },
	{ label: '低危', value: '2' },
];
const filterChangeType = [
	{ label: '结构变更', value: 'structure' },
	{ label: '文本变更', value: 'text' },
	{ label: '资源变更', value: 'resource' },
];
const defaultFilter = {
	page: 1,
	limit: 10,
};
const levelColor = {
	5: '#D5342F',
	4: '#F04038',
	3: '#F18246',
	2: '#FCD94A',
};

function Detail({
	tid,
	atid,
	data,
	jid,
	taskType,
	isHistory,
	webDataLoading,
	enableTaskType,
	refresh,
}) {
	const resD = JSON.parse(sessionStorage.resD).feature;
	const [filter, setFilter] = React.useState(defaultFilter);
	const [tableData, setTableData] = React.useState({
		data: [],
		total: 0,
	});

	const colum = [
		{
			title: '风险地址',
			dataIndex: 'affects',
			key: 'affects',
			render(affects) {
				return <CopyBoard text={affects} className={'db'} />;
			},
		},
		{
			title: '变更类型',
			dataIndex: 'changeType',
			key: 'changeType',
		},
		{
			title: '威胁等级',
			dataIndex: 'level',
			key: 'level',
			render(e) {
				const levelName = optionData.filter(item => {
					return +item.value === +e;
				})[0].label;
				return <span style={{ color: levelColor[e] }}>{levelName}</span>;
			},
		},
		{
			title: '操作',
			dataIndex: 'name',
			key: 'name',
			render(e, row) {
				return (
					<>
						<Link
							className={s.item}
							to={{
								pathname: '/job-manage/web-task/change-check-detail',
								state: {
									category: row.category,
									id: row.task_id,
									warningId: row._id,
									atid,
									isHistory,
									taskType,
								},
							}}
						>
							查看详情
						</Link>
						<IgnoreRiskConfirm
							className={'ml5'}
							data={{ task_id: row.task_id, warning_ids: [row._id] }}
							refresh={() => refresh(true)}
							isChangeType={true}
							changeTypes={row.changeTypeEn}
						/>
					</>
				);
			},
		},
	];

	const getData = () => {
		const totalData = data?.warnings?.reduce((total, item) => {
			let i = cloneDeep(item);
			i.changeTypeEn = [];
			let changeTypes = filterChangeType.reduce((types, t) => {
				if (t.value in i.detail) {
					types.push(t.label.substring(0, 2));
					i.changeTypeEn.push(t.value);
				}
				return types;
			}, []);
			i.changeType = changeTypes.join('、') + '变更';
			i.task_id = data.task_id;
			i.key = i._id;
			if (i.level.toString() === '1') {
				i.level = 2;
			}
			if (filter.affects && item.affects.indexOf(filter.affects) === -1) {
				i = null;
			}
			if (filter.title && item.title.indexOf(filter.title) === -1) {
				i = null;
			}
			if (filter.level && item.level.toString() !== filter.level) {
				i = null;
			}
			if (filter.changeType && !(filter.changeType in item.detail)) {
				i = null;
			}
			if (i) total.push(i);
			return total;
		}, []);
		const resultList = [];
		const limit = filter.limit || 10;
		if (totalData?.length > 0) {
			Array(Math.ceil(totalData.length / limit))
				.fill('')
				.map((i, k) => {
					resultList.push(totalData.slice(k * limit, k * limit + limit));
				});
		}
		setTableData({
			data: resultList,
			total: totalData?.length || 0,
		});
	};

	const [selectedRows, setSelectedRows] = useState([]);
	const onSelectAll = (selected, sr, changeRows) => {
		const changeKeys = changeRows.map(i => i._id);
		if (!selected) {
			setSelectedRows(selectedRows.filter(i => !changeKeys.includes(i)));
		} else {
			setSelectedRows(Array.from(new Set(selectedRows.concat(changeKeys))));
		}
	};
	const onSelect = (r, selected, ss, n) => {
		if (!selected) {
			setSelectedRows(selectedRows.filter(i => i !== r._id));
		} else {
			setSelectedRows(Array.from(new Set(selectedRows.concat([r._id]))));
		}
	};
	const handleChangeSearch = e => {
		e && setFilter({ ...filter, ...e });
	};

	const generateEmptyText = () => {
		let text = '暂无数据';
		if (webDataLoading) return text;
		if (Object.keys(data).length > 0) {
			if (data?.task_session_id) {
				text = '暂无数据';
			} else {
				text = <div>任务数据已过期，您可 重新下发监测任务</div>;
			}
		} else if (taskType === 'manual' && !resD.contentManualTask) {
			text = '当前套餐不支持该监测项，请先升级套餐。';
		} else if (taskType === 'schedule' && !resD.contentTask) {
			text = '当前套餐不支持该监测项，请先升级套餐。';
		} else if (Object.keys(data).length === 0) {
			if (enableTaskType.indexOf('changeCheck') > -1) {
				text = (
					<span style={{ color: 'rgba(0,0,0,.5)' }}>当前任务正在监测中...</span>
				);
			} else {
				text = '当前任务未启用该监测项，请前往任务配置进行调整。';
			}
		}
		return text;
	};

	useEffect(() => {
		getData();
	}, [filter, data]);

	return (
		<div className={s.tableMain}>
			{!isHistory &&
				(Object.keys(data).length > 0 ||
					enableTaskType.indexOf('changeCheck') > -1) && (
					<div className={cn(s.flex, s.aic)}>
						<Icon type="time" />
						<span className={cn(s.pl10, s.pr20)}>
							{Object.keys(data).length === 0 || !data?.task_session_id
								? '- -'
								: moment(data?.time_info?.end_time).format(
										'YYYY-MM-DD HH:mm:ss'
								  )}
						</span>
						{taskType !== 'manual' &&
							Object.keys(data).length > 0 &&
							data?.task_session_id && (
								<Link
									to={{
										pathname: '/job-manage/web-task/history',
										search: `asset_task_id=${atid}&task_id=${data?.task_id}&task_types=change_check`,
									}}
								>
									查看历史任务
								</Link>
							)}
					</div>
				)}
			<div className={cn(s.search, 'aic')}>
				<div className={'df aic fs16 blackLineColor'}>
					篡改
					<Tooltip
						placement="top"
						overlay={
							<div>
								<div>威胁等级划分规则</div>
								<div>
									高危：业务系统的重点关注资源存在变更，或变更内容中包括自定义违规词
								</div>
								<div>低危：其他变更情况</div>
							</div>
						}
					>
						<Icon className="ml5 mr5 cp" type="question" />
					</Tooltip>
					<span className={s.num}>({tableData.total || 0})</span>
				</div>
				<div className={s.selectContainer}>
					<Select
						placeholder="变更类型"
						className={s.item}
						value={filter.changeType}
						allowClear={true}
						getPopupContainer={triggerNode => triggerNode}
						onChange={changeType => {
							handleChangeSearch({ changeType });
						}}
					>
						{filterChangeType.map(e => (
							<Option key={e.value} value={e.value}>
								{e.label}
							</Option>
						))}
					</Select>
					<Select
						placeholder="威胁等级"
						className={s.item}
						value={filter.level}
						allowClear={true}
						getPopupContainer={triggerNode => triggerNode}
						onChange={level => {
							handleChangeSearch({ level });
						}}
					>
						{optionData.map(e => (
							<Option key={e.value} value={e.value}>
								{e.label}
							</Option>
						))}
					</Select>
					<Button
						className={'primary-btn'}
						onClick={() => {
							setFilter(defaultFilter);
						}}
					>
						重置
					</Button>
				</div>
			</div>
			<Table
				className={s.newtable}
				pro
				columns={colum}
				key={Math.random().toString(36).slice(-6)}
				data={tableData.data[filter.page - 1] || []}
				rowSelection={{
					selectedRowKeys: selectedRows,
					width: 50,
					onSelect,
					onSelectAll,
				}}
				empty={
					<EmptyData
						emptyType={
							Object.keys(data).length === 0
								? enableTaskType.indexOf('changeCheck') > -1
									? 'dataLoading'
									: 'noPrmission'
								: 'noData'
						}
						text={(function () {
							let text = '暂无数据';
							if (webDataLoading) return text;
							if (Object.keys(data).length > 0) {
								if (data?.task_session_id) {
									text = '暂无数据';
								} else {
									text = <div>任务数据已过期，您可 重新下发监测任务</div>;
								}
							} else if (taskType === 'manual' && !resD.vulManualTask) {
								text = '当前套餐不支持该监测项，请先升级套餐。';
							} else if (taskType === 'schedule' && !resD.vulTask) {
								text = '当前套餐不支持该监测项，请先升级套餐。';
							} else if (Object.keys(data).length === 0) {
								if (enableTaskType.indexOf('vul') > -1) {
									text = (
										<span style={{ color: 'rgba(0,0,0,.5)' }}>
											当前任务正在监测中...
										</span>
									);
								} else {
									text = '当前任务未启用该监测项，请前往任务配置进行调整。';
								}
							}
							return text;
						})()}
						className={s.nobor}
					/>
				}
			/>
			<div>
				<div className={cn('df aic jcsb mt10')}>
					<IgnoreRiskConfirm
						className={'p0'}
						text="批量忽略"
						disabled={selectedRows?.length === 0}
						isChangeType={true}
						data={{ warning_ids: selectedRows, task_id: data?.task_id }}
						refresh={_ => {
							refresh(true);
							setSelectedRows([]);
						}}
						warningData={data?.warnings || []}
					/>
					{tableData.total > 10 && (
						<Pagination
							total={tableData.total}
							current={filter.page || 1}
							pageSize={filter.limit || 10}
							pageSizeOptions={[10, 20, 50]}
							showSizeChanger
							showQuickJumper
							showTotal={total => `共${total}条`}
							onChange={(page, limit) => {
								handleChangeSearch({ page, limit });
							}}
						/>
					)}
				</div>
			</div>
		</div>
	);
}

Detail.propTypes = {
	tid: PropTypes.any,
	atid: PropTypes.any,
};
export default withRouter(Detail);
